package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.king.image.imageviewer.ImageViewer;
import com.king.image.imageviewer.loader.GlideImageLoader;
import com.stark.picselect.entity.SelectMediaEntity;

import java.util.ArrayList;
import java.util.List;

import flc.ast.App;
import flc.ast.BaseAc;
import flc.ast.Content;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.AlbumAdapter1;
import flc.ast.adapter.AlbumPicAdapter;
import flc.ast.bean.MyAlbumBean;
import flc.ast.bean.MyPictureBean;
import flc.ast.databinding.ActivityAlbumBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.CardLayoutManagerLan;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.SPUtil;

public class AlbumActivity extends BaseAc<ActivityAlbumBinding> {

    public static String albumId = "";
    public static boolean isPub;
    private List<MyAlbumBean> listSp = new ArrayList<>();
    private List<MyPictureBean> listShow = new ArrayList<>();
    private AlbumPicAdapter albumPicAdapter;
    private Dialog myMoreDialog;
    private Dialog myRenameDialog;
    private EditText dialogRename;
    private Dialog myDeleteDialog;
    private Dialog myDeleteAlbumDialog;
    private boolean isEdit = false;
    private boolean isAllSel=false;
    private List<String> listSel = new ArrayList<>();


    @Override
    protected int onCreate() {
        return R.layout.activity_album;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        mDataBinding.ivAlbumBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.rvAlbumPicList.setLayoutManager(new GridLayoutManager(mContext, 3));
        albumPicAdapter = new AlbumPicAdapter();
        mDataBinding.rvAlbumPicList.setAdapter(albumPicAdapter);
        albumPicAdapter.setOnItemClickListener(this);
        mDataBinding.ivAlbumAdd.setOnClickListener(this);
        mDataBinding.ivAlbumMore.setOnClickListener(this);
        mDataBinding.tvAlbumAllSel.setOnClickListener(this);
        mDataBinding.ivAlbumDelete.setOnClickListener(this);
        //更多弹框
        moreDialog();
        //重命名弹框
        renameDialog();
        //删除弹框
        deleteDialog();
        //删除相册弹窗
        deleteAlbumDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivAlbumAdd:
                Intent intent = new Intent(this, SelPicActivity.class);
                startActivityForResult(intent, Content.REQUEST_ADD);
                break;
            case R.id.ivAlbumMore:
                myMoreDialog.show();
                break;
            case R.id.tvDialogMoreCancel:
                myMoreDialog.dismiss();
                break;
            case R.id.tvDialogMoreAllSel://多选
                myMoreDialog.dismiss();
                isEdit = true;
                mDataBinding.ivAlbumMore.setVisibility(View.GONE);
                mDataBinding.tvAlbumAllSel.setVisibility(View.VISIBLE);
                mDataBinding.rlAlbumDeleteView.setVisibility(View.VISIBLE);
                albumPicAdapter.setEdit(true);
                albumPicAdapter.notifyDataSetChanged();
                break;
            case R.id.tvAlbumAllSel:
                isAllSel=!isAllSel;
                mDataBinding.tvAlbumAllSel.setVisibility(View.VISIBLE);
                mDataBinding.tvAlbumAllSel.setText(isAllSel?getString(R.string.cancel_all_sel):getString(R.string.all_sel));
                if (isAllSel){
                    for (MyPictureBean bean : albumPicAdapter.getValidData()) {
                        bean.setSelect(true);
                        listSel.add(bean.getPath());
                    }
                    albumPicAdapter.notifyDataSetChanged();
                }else{
                    for (MyPictureBean bean : albumPicAdapter.getValidData()) {
                        bean.setSelect(false);
                    }
                    listSel.clear();
                    albumPicAdapter.notifyDataSetChanged();
                }
                break;
            case R.id.ivAlbumDelete://删除图片
                myDeleteDialog.show();
                break;
            case R.id.tvDialogDeleteCancel:
                myDeleteDialog.dismiss();
                break;
            case R.id.tvDialogDeleteConfirm:
                deleteAlbum();
                myDeleteDialog.dismiss();
                isEdit = false;
                mDataBinding.ivAlbumMore.setVisibility(View.VISIBLE);
                mDataBinding.tvAlbumAllSel.setVisibility(View.GONE);
                mDataBinding.rlAlbumDeleteView.setVisibility(View.GONE);
                albumPicAdapter.setEdit(false);
                break;
            case R.id.tvDialogMoreRename:
                myMoreDialog.dismiss();
                dialogRename.setText("");
                myRenameDialog.show();
                break;
            case R.id.tvDialogRenameConfirm:
                renameAlbum();
                break;
            case R.id.tvDialogRenameCancel:
                myRenameDialog.dismiss();
                break;
            case R.id.tvDialogMoreClear://删除相册
                myMoreDialog.dismiss();
                myDeleteAlbumDialog.show();
                break;
            case R.id.tvDialogDeleteAlbumConfirm:
                myDeleteAlbumDialog.dismiss();
                delete();
                break;
            case R.id.tvDialogDeleteAlbumCancel:
                myDeleteAlbumDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit){
            if (albumPicAdapter.getItem(position).isSelect()) {
                albumPicAdapter.getItem(position).setSelect(false);
                listSel.remove(albumPicAdapter.getItem(position).getPath());
            } else {
                albumPicAdapter.getItem(position).setSelect(true);
                listSel.add(albumPicAdapter.getItem(position).getPath());
            }
            albumPicAdapter.notifyItemChanged(position);
        }else {
            ImageViewer.load(listShow.get(position).getPath())//要加载的图片数据，单张或多张
                        .selection(0)//当前选中位置，默认：0
                        .indicator(false)//是否显示指示器，默认不显示
                        .imageLoader(new GlideImageLoader())//加载器，imageLoader必须配置，目前内置的有GlideImageLoader或PicassoImageLoader，也可以自己实现
                        .theme(R.style.ImageViewerTheme)//设置主题风格，默认：R.style.ImageViewerTheme
                        .orientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//设置屏幕方向,默认：ActivityInfo.SCREEN_ORIENTATION_BEHIND
                        .start(AlbumActivity.this);//activity or fragment, 跳转时的共享元素视图
        }
    }

    @Override
    protected void initData() {
        if (isPub) {
            getData();
        } else {
            getPriData();
        }
    }

    private void getData() {
        listShow.clear();
        List<String> listPath = new ArrayList<>();
        listSp = AppSpUtils.getAlbumList();
        if (listSp != null && listSp.size() > 0) {
            for (MyAlbumBean bean : listSp) {
                if (bean.getId().equals(albumId)) {
                    mDataBinding.tvAlbumTitle.setText(bean.getName());
                    listPath.addAll(bean.getListData());
                    break;
                }
            }
        }
        if (listPath.size() > 0) {
            for (String path : listPath) {
                listShow.add(new MyPictureBean(path, false));
            }
            albumPicAdapter.setList(listShow);
            mDataBinding.rvAlbumPicList.setVisibility(View.VISIBLE);
            mDataBinding.tvAlbumNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvAlbumPicList.setVisibility(View.GONE);
            mDataBinding.tvAlbumNoData.setVisibility(View.VISIBLE);
        }
    }

    private void getPriData() {
        listShow.clear();
        List<String> listPath = new ArrayList<>();
        listSp = AppSpUtils.getPriAlbumList();
        if (listSp != null && listSp.size() > 0) {
            for (MyAlbumBean bean : listSp) {
                if (bean.getId().equals(albumId)) {
                    mDataBinding.tvAlbumTitle.setText(bean.getName());
                    listPath.addAll(bean.getListData());
                    break;
                }
            }
        }
        if (listPath.size() > 0) {
            for (String path : listPath) {
                listShow.add(new MyPictureBean(path, false));
            }
            albumPicAdapter.setList(listShow);
            mDataBinding.rvAlbumPicList.setVisibility(View.VISIBLE);
            mDataBinding.tvAlbumNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvAlbumPicList.setVisibility(View.GONE);
            mDataBinding.tvAlbumNoData.setVisibility(View.VISIBLE);
        }
    }

    //删除相册图片
    private void deleteAlbum() {
        if (isPub){
            List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
            if (listSp != null && listSp.size() > 0) {
                for (MyAlbumBean bean : listSp) {
                    if (bean.getId().equals(albumId)) {
                        bean.getListData().removeAll(listSel);
                        break;
                    }
                }
                AppSpUtils.saveAlbumList(listSp);
            }
            getData();
        }else{
            List<MyAlbumBean> listSp = AppSpUtils.getPriAlbumList();
            if (listSp != null && listSp.size() > 0) {
                for (MyAlbumBean bean : listSp) {
                    if (bean.getId().equals(albumId)) {
                        bean.getListData().removeAll(listSel);
                        break;
                    }
                }
                AppSpUtils.savePriAlbumList(listSp);
            }
            getPriData();
        }
    }

    //删除相册
    private void delete() {
        if (isPub){
            List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
            if (listSp != null && listSp.size() > 0) {
                for (int i = 0; i < listSp.size(); i++) {
                    if (listSp.get(i).getId().equals(albumId)){
                        listSp.remove(i);
                    }
                }
                AppSpUtils.saveAlbumList(listSp);
            }
        }else{
            List<MyAlbumBean> listSp = AppSpUtils.getPriAlbumList();
            if (listSp != null && listSp.size() > 0) {
                for (int i = 0; i < listSp.size(); i++) {
                    if (listSp.get(i).getId().equals(albumId)){
                        listSp.remove(i);
                    }
                }
                AppSpUtils.savePriAlbumList(listSp);
            }
        }
        startActivity(HomeActivity.class);
    }

    //重命名相册
    private void renameAlbum() {
        String rename = dialogRename.getText().toString();
        if (TextUtils.isEmpty(rename)) {
            ToastUtils.showShort(R.string.please_input_album_name);
            return;
        }
        myRenameDialog.dismiss();
        mDataBinding.tvAlbumTitle.setText(rename);
        if (isPub){
            List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
            if (listSp != null && listSp.size() > 0) {
                for (MyAlbumBean bean : listSp) {
                    if (bean.getId().equals(albumId)) {
                        bean.setName(rename);
                        break;
                    }
                }
                AppSpUtils.saveAlbumList(listSp);
            }
        }else{
            List<MyAlbumBean> listSp = AppSpUtils.getPriAlbumList();
            if (listSp != null && listSp.size() > 0) {
                for (MyAlbumBean bean : listSp) {
                    if (bean.getId().equals(albumId)) {
                        bean.setName(rename);
                        break;
                    }
                }
                AppSpUtils.savePriAlbumList(listSp);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Content.REQUEST_ADD) {
            List<String> listPath = (List<String>) data.getSerializableExtra(Content.LIST_PATH);
            if (listPath != null && listPath.size() > 0) {
                if (isPub) {
                    List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
                    if (listSp != null && listSp.size() > 0) {
                        for (MyAlbumBean bean : listSp) {
                            if (bean.getId().equals(albumId)) {
                                if (bean.getListData() != null && bean.getListData().size() > 0) {
                                    bean.getListData().addAll(listPath);
                                } else {
                                    bean.setListData(listPath);
                                }
                                break;
                            }
                        }
                        AppSpUtils.saveAlbumList(listSp);
                    }
                    getData();
                } else {
                    List<MyAlbumBean> listSp = AppSpUtils.getPriAlbumList();
                    if (listSp != null && listSp.size() > 0) {
                        for (MyAlbumBean bean : listSp) {
                            if (bean.getId().equals(albumId)) {
                                if (bean.getListData() != null && bean.getListData().size() > 0) {
                                    bean.getListData().addAll(listPath);
                                } else {
                                    bean.setListData(listPath);
                                }
                                break;
                            }
                        }
                        AppSpUtils.savePriAlbumList(listSp);
                    }
                    getPriData();
                }
            }
        }
    }

    //更多弹框
    private void moreDialog() {
        myMoreDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_more, null);
        myMoreDialog.setContentView(inflate);
        myMoreDialog.setCancelable(true);
        //获取当前Activity所在的窗体
        Window dialogWindow = myMoreDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.95);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogRename = inflate.findViewById(R.id.tvDialogMoreRename);
        TextView dialogAllSel = inflate.findViewById(R.id.tvDialogMoreAllSel);
        TextView dialogClear = inflate.findViewById(R.id.tvDialogMoreClear);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogMoreCancel);
        dialogRename.setOnClickListener(this);
        dialogAllSel.setOnClickListener(this);
        dialogClear.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(false);
        //获取当前Activity所在的窗体
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogClose = inflate.findViewById(R.id.tvDialogRenameCancel);
        TextView dialogCom = inflate.findViewById(R.id.tvDialogRenameConfirm);
        dialogClose.setOnClickListener(this);
        dialogCom.setOnClickListener(this);
        dialogRename = inflate.findViewById(R.id.etDialogRename);
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(false);
        //获取当前Activity所在的窗体
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogClose = inflate.findViewById(R.id.tvDialogDeleteCancel);
        TextView dialogCom = inflate.findViewById(R.id.tvDialogDeleteConfirm);
        dialogClose.setOnClickListener(this);
        dialogCom.setOnClickListener(this);
    }

    //删除相册弹框
    private void deleteAlbumDialog() {
        myDeleteAlbumDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete_album, null);
        myDeleteAlbumDialog.setContentView(inflate);
        myDeleteAlbumDialog.setCancelable(false);
        //获取当前Activity所在的窗体
        Window dialogWindow = myDeleteAlbumDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogClose = inflate.findViewById(R.id.tvDialogDeleteAlbumCancel);
        TextView dialogCom = inflate.findViewById(R.id.tvDialogDeleteAlbumConfirm);
        dialogClose.setOnClickListener(this);
        dialogCom.setOnClickListener(this);
    }

}